package com.gzhryc.net_marketing.core;

import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.CloudGoodsAPIService;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsTypeListResponse;
import com.gzhryc.net_marketing.core.models.GoodsTypeItem;

import java.util.List;

public class GoodsTypeUtils {

    static Logger log = Logger.getLogger(GoodsTypeUtils.class);

    static List<GoodsTypeItem> goodsTypeItems;

    public static void initial(){
        GoodsTypeListResponse apiResp = CloudGoodsAPIService.self().findGoodsTypeList();
        if(apiResp != null && DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())){
            goodsTypeItems = apiResp.getBody().getItems();
        }else{
            log.error("初始化商品类型数据失败");
        }
    }

    public static List<GoodsTypeItem> getGoodsTypeItems(){
        return goodsTypeItems;
    }

    /**
     * 根据Code获取商品类型名称，只支持3层
     * @param codes
     * @return
     */
    public static String[] findByCodes(String[] codes){
        if(codes != null && codes.length > 0 && goodsTypeItems != null && goodsTypeItems.size() > 0){
            String[] names = new String[codes.length];
            for(GoodsTypeItem goodsTypeItem : goodsTypeItems){
                if(goodsTypeItem.getCode().equals(codes[0])){
                    names[0] = goodsTypeItem.getName();
                    if(codes.length >= 2 && goodsTypeItem.getChildren() != null && goodsTypeItem.getChildren().size() > 0){
                        for(GoodsTypeItem child1 :  goodsTypeItem.getChildren()){
                            if(child1.getCode().equals(codes[1])){
                                names[1] = child1.getName();
                                if(codes.length >= 3 && child1.getChildren() != null && child1.getChildren().size() > 0){
                                    for(GoodsTypeItem child2 :  child1.getChildren()) {
                                        if (child2.getCode().equals(codes[2])) {
                                            names[2] = child2.getName();
                                            break;
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                    break;
                }
            }
            return names;
        }
        return null;
    }

    public static GoodsTypeItem getByCode(String code){
        if(code != null && goodsTypeItems != null && goodsTypeItems.size() > 0) {
            for (GoodsTypeItem goodsTypeItem : goodsTypeItems) {
                if (goodsTypeItem.getCode().equals(code)) {
                    return goodsTypeItem;
                }
            }
        }
        return null;
    }
}
